package com.liuhengjia.interceptors;

import com.liuhengjia.util.Jwts;
import com.liuhengjia.util.ThreadLocals;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 令牌验证
        try {
            String jwtStr = request.getHeader("Authorization");
            ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
            String redisToken = stringStringValueOperations.get(jwtStr);
            if (redisToken == null) {
                throw new RuntimeException();
            }
            Map<String, Object> decodeMap = Jwts.parseToken(jwtStr);
            ThreadLocals.set(decodeMap);// ThreadLocal 存数据
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocals.remove();// 释放 ThreadLocal
    }
}
